package org.example.seata.bs.auth.handler.check;

import lombok.extern.slf4j.Slf4j;
import org.example.seata.common.security.constant.AuthTypeConst;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 用户名密码登录校验
 *
 * @author hzq
 * @date 2021/12/16 13:51
 */
@Slf4j
@Component
public class UsernameCheckAuthHandler implements CheckAuthHandler {

    private static final PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    public void check(String principal, String credentials) {

        log.info("明文:{},密文:{}", principal, credentials);

        boolean matches = passwordEncoder.matches(principal, credentials);
        if (!matches) {
            throw new BadCredentialsException("用户名或密码错误");
        }
    }

    @Override
    public boolean supportType(String checkType) {
        return AuthTypeConst.USERNAME.equals(checkType);
    }
}
